/**
 * 生成井的SVG俯视图（改进版，通道在面中心且不重叠）
 * @param {Object} wellData 井的数据
 * @param {Array} channels 通道数组
 * @param {Object} statusColors 状态颜色配置
 * @returns {string} SVG字符串
 */
function generateWellSVG(wellData, channels, statusColors) {
  // 参数验证
  if (!wellData || !channels || !statusColors) {
    throw new Error('缺少必要参数');
  }

  // SVG尺寸和中心点
  const svgSize = 800; // 增大SVG尺寸以容纳更多内容
  const center = svgSize / 2;
  const wellRadius = 250;
  const channelRadius = 30;
  const holeRadius = 8;
  const connectionStrokeWidth = 3;
  const channelOffset = 60; // 通道距离井边的距离

  // 计算八角形的顶点坐标和面中心点
  function getOctagonPoint(index, radius = wellRadius) {
    const angle = (Math.PI / 4) * index - Math.PI / 2;
    return {
      x: center + radius * Math.cos(angle),
      y: center + radius * Math.sin(angle)
    };
  }

  // 获取面的中心点（用于放置通道）
  function getFaceCenterPoint(index) {
    const point1 = getOctagonPoint(index);
    const point2 = getOctagonPoint((index + 1) % 8);
    return {
      x: (point1.x + point2.x) / 2,
      y: (point1.y + point2.y) / 2
    };
  }

  // 获取通道位置（在面中心向外延伸）
  function getChannelPosition(faceIndex) {
    const faceCenter = getFaceCenterPoint(faceIndex);
    const wellEdge = getOctagonPoint(faceIndex);

    // 计算从面中心向外延伸的方向向量
    const dx = faceCenter.x - center;
    const dy = faceCenter.y - center;
    const length = Math.sqrt(dx * dx + dy * dy);
    const normalizedDx = dx / length;
    const normalizedDy = dy / length;

    return {
      x: faceCenter.x + normalizedDx * channelOffset,
      y: faceCenter.y + normalizedDy * channelOffset
    };
  }

  // 生成八角形路径
  function generateOctagonPath(radius) {
    return Array.from({ length: 8 }, (_, i) => {
      const point = getOctagonPoint(i, radius);
      return `${i === 0 ? 'M' : 'L'}${point.x},${point.y}`;
    }).join(' ') + ' Z';
  }

  // 查找通道
  function findChannel(id) {
    return channels.find(c => c.id === id);
  }

  // 查找管孔
  function findHole(id) {
    for (const channel of channels) {
      const hole = channel.holes.find(h => h.id === id);
      if (hole) return { ...hole, channelId: channel.id };
    }
    return null;
  }

  // 生成通道的SVG元素
  function generateChannelElements() {
    let elements = [];
    const occupiedAngles = new Set(); // 记录已占用的角度

    for (let i = 0; i < 8; i++) {
      const faceKey = `face${i + 1}`;
      const channelId = wellData[faceKey];
      if (!channelId) continue;

      const channel = findChannel(channelId);
      if (!channel) continue;

      // 获取通道位置
      const channelPos = getChannelPosition(i);

      // 通道连接线（从井边到通道）
      const faceCenter = getFaceCenterPoint(i);
      elements.push(`<line x1="${faceCenter.x}" y1="${faceCenter.y}" x2="${channelPos.x}" y2="${channelPos.y}" stroke="#999" stroke-width="2" />`);

      // 通道圆
      elements.push(`<circle cx="${channelPos.x}" cy="${channelPos.y}" r="${channelRadius}" fill="#f5f5f5" stroke="#666" stroke-width="2" />`);

      // 通道ID文本
      elements.push(`<text x="${channelPos.x}" y="${channelPos.y}" text-anchor="middle" dominant-baseline="middle" font-size="12" fill="#333">${channel.id}</text>`);

      // 记录这个通道的角度，防止管孔重叠
      occupiedAngles.add(i);
    }
    return elements.join('\n');
  }

  // 生成管孔连接线
  function generateConnectionElements() {
    if (!wellData.connections || wellData.connections.length === 0) return '';

    let elements = [];
    for (const connection of wellData.connections) {
      if (connection.length < 2) continue;

      // 获取第一个管孔信息
      const hole1 = findHole(connection[0]);
      const hole2 = findHole(connection[1]);
      if (!hole1 || !hole2) continue;

      // 获取通道
      const channel1 = findChannel(hole1.channelId);
      const channel2 = findChannel(hole2.channelId);
      if (!channel1 || !channel2) continue;

      // 获取通道在井上的面索引
      const channel1Face = Object.keys(wellData).find(key => wellData[key] === channel1.id);
      const channel2Face = Object.keys(wellData).find(key => wellData[key] === channel2.id);
      if (!channel1Face || !channel2Face) continue;

      const channel1Index = parseInt(channel1Face.replace('face', '')) - 1;
      const channel2Index = parseInt(channel2Face.replace('face', '')) - 1;

      // 计算通道中心点
      const channel1Pos = getChannelPosition(channel1Index);
      const channel2Pos = getChannelPosition(channel2Index);

      // 计算管孔在通道中的位置
      const hole1Index = channel1.holes.findIndex(h => h.id === hole1.id);
      const hole2Index = channel2.holes.findIndex(h => h.id === hole2.id);

      // 计算管孔位置（均匀分布在通道圆周上）
      const angle1 = (Math.PI * 2 * hole1Index / channel1.holes.length);
      const angle2 = (Math.PI * 2 * hole2Index / channel2.holes.length);

      const hole1Point = {
        x: channel1Pos.x + channelRadius * Math.cos(angle1),
        y: channel1Pos.y + channelRadius * Math.sin(angle1)
      };

      const hole2Point = {
        x: channel2Pos.x + channelRadius * Math.cos(angle2),
        y: channel2Pos.y + channelRadius * Math.sin(angle2)
      };

      // 获取管孔状态颜色
      const status1 = hole1.status;
      const status2 = hole2.status;
      const color1 = statusColors[status1] || statusColors['0'];
      const color2 = statusColors[status2] || statusColors['0'];

      // 绘制连接线
      elements.push(`<path d="M${hole1Point.x},${hole1Point.y} L${hole2Point.x},${hole2Point.y}" stroke="${color1.outer}" stroke-width="${connectionStrokeWidth}" fill="none" />`);

      // 绘制管孔
      elements.push(`<circle cx="${hole1Point.x}" cy="${hole1Point.y}" r="${holeRadius}" fill="${color1.inner}" stroke="${color1.outer}" stroke-width="2" />`);
      elements.push(`<circle cx="${hole2Point.x}" cy="${hole2Point.y}" r="${holeRadius}" fill="${color2.inner}" stroke="${color2.outer}" stroke-width="2" />`);

      // 管孔ID文本（智能放置，避免重叠）
      const textOffset1 = holeRadius + 12;
      const textOffset2 = holeRadius + 12;

      elements.push(`<text x="${hole1Point.x}" y="${hole1Point.y + textOffset1}" text-anchor="middle" font-size="10" fill="#333">${hole1.id}</text>`);
      elements.push(`<text x="${hole2Point.x}" y="${hole2Point.y + textOffset2}" text-anchor="middle" font-size="10" fill="#333">${hole2.id}</text>`);
    }
    return elements.join('\n');
  }

  // 生成状态图例
  function generateLegend() {
    let elements = ['<g transform="translate(20, 20)">'];
    elements.push('<rect x="0" y="0" width="180" height="150" fill="white" stroke="#ccc" rx="5" />');
    elements.push('<text x="90" y="20" text-anchor="middle" font-weight="bold">状态图例</text>');

    let y = 40;
    for (const [status, config] of Object.entries(statusColors)) {
      elements.push(`<circle cx="20" cy="${y}" r="6" fill="${config.inner}" stroke="${config.outer}" stroke-width="2" />`);
      elements.push(`<text x="35" y="${y + 5}" font-size="12">${config.desc}</text>`);
      y += 25;
    }

    elements.push('</g>');
    return elements.join('\n');
  }

  // 构建SVG
  const svg = `
    <svg width="${svgSize}" height="${svgSize}" viewBox="0 0 ${svgSize} ${svgSize}" xmlns="http://www.w3.org/2000/svg">
      <!-- 背景 -->
      <rect width="100%" height="100%" fill="#f9f9f9" />
      
      <!-- 井八角形 -->
      <path d="${generateOctagonPath(wellRadius)}" fill="#e0e0e0" stroke="#666" stroke-width="2" />
      
      <!-- 井内部八角形 -->
      <path d="${generateOctagonPath(wellRadius - 30)}" fill="#f5f5f5" stroke="#666" stroke-width="1" />
      
      <!-- 井ID -->
      <text x="${center}" y="${center}" text-anchor="middle" dominant-baseline="middle" font-size="24" fill="#333">井 ${wellData.id}</text>
      
      <!-- 面编号（调试用） -->
      ${Array.from({ length: 8 }, (_, i) => {
    const point = getFaceCenterPoint(i);
    return `<text x="${point.x}" y="${point.y}" text-anchor="middle" dominant-baseline="middle" font-size="12" fill="#999">面${i + 1}</text>`;
  }).join('\n')}
      
      <!-- 通道 -->
      ${generateChannelElements()}
      
      <!-- 管孔连接 -->
      ${generateConnectionElements()}
      
      <!-- 图例 -->
      ${generateLegend()}
    </svg>
  `;

  return svg;
}

// 示例使用
const wellData = {
  id: 1,
  face1: null,
  face2: "chanel1",
  face3: null,
  face4: null,
  face5: "chanel2",
  face6: null,
  face7: "chanel3",
  face8: null,
  connections: [
    ['hole1', 'hole3'],
    ['hole2', 'hole4'],
    ['hole5', 'hole7']
  ]
};

const channels = [
  {
    id: 'chanel1',
    holes: [
      { id: "hole1", status: 0 },
      { id: "hole2", status: 1 },
      { id: "hole8", status: 2 }
    ]
  },
  {
    id: 'chanel2',
    holes: [
      { id: "hole3", status: 0 },
      { id: "hole4", status: 1 },
      { id: "hole9", status: 3 }
    ]
  },
  {
    id: 'chanel3',
    holes: [
      { id: "hole5", status: 4 },
      { id: "hole6", status: 2 },
      { id: "hole7", status: 1 }
    ]
  }
];

const statusColors = {
  '0': { inner: '#fff', outer: '#99bbb7', desc: '未分配' },
  '1': { inner: '#fff', outer: '#ffd04b', desc: '已分配' },
  '2': { inner: '#000', outer: '#000', desc: '已使用' },
  '3': { inner: '#fff', outer: '#a80e09', desc: '已损坏' },
  '4': { inner: '#fff', outer: '#800080', desc: '通信' }
};

// 生成SVG并插入到文档中
const svg = generateWellSVG(wellData, channels, statusColors);
document.body.innerHTML = svg;